<template>
  <div class="update-gender">
    <van-picker
      title="标题"
      show-toolbar
      :columns="columns"
      @confirm="onConfirm"
      @cancel="$emit('close')"
      :default-index="value"
      @change="onPickerChange"
    />
  </div>
</template>
<script>
import { updateUserProfile } from '@/api/user'
export default {
  name: 'UpdateGender',
  components: {},
  props: {
    value: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      columns: ['男', '女'],
      localGender: this.value
    }
  },
  computed: {},
  watch: {},
  methods: {
    async onConfirm() {
      // 增加loading 加载状态，防止用户反复点击
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })
      try {
        const localGender = this.localGender
        // 发送参数，请求更新
        await updateUserProfile({
          gender: localGender
        })
        this.$emit('input', localGender) // 更新视图 v-model 方法操作
        this.$toast.success('性别修改成功') // 提示成功
        this.$emit('close') // 关闭弹出层
      } catch (err) {
        this.$toast('数据获取失败')
      }
    },
    // 通过 onchange 事件获取选择男女对应的索引值
    onPickerChange(picker, values, index) {
      this.localGender = index
    }
  },
  created() {},
  mounted() {}
}
</script>
<style scoped lang="less"></style>
